package com.arong.biBackend.controller;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import com.arong.biBackend.bizmq.BiMessageProducer;
import com.arong.biBackend.constant.FileConstant;
import com.arong.biBackend.manager.AIManager;
import com.arong.biBackend.manager.CosManager;
import com.arong.biBackend.manager.GuavaRetryManager;
import com.arong.biBackend.manager.RedisLimiterManager;
import com.arong.biBackend.mapper.ChartMapper;
import com.arong.biBackend.model.dto.chart.*;
import com.arong.biBackend.model.dto.db.DetailTableDto;
import com.arong.biBackend.model.dto.file.UploadFileRequest;
import com.arong.biBackend.model.entity.Chart;
import com.arong.biBackend.model.entity.User;
import com.arong.biBackend.model.enums.FileUploadBizEnum;
import com.arong.biBackend.model.vo.BIResponse;
import com.arong.biBackend.utils.ExcelUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.arong.biBackend.annotation.AuthCheck;
import com.arong.biBackend.common.BaseResponse;
import com.arong.biBackend.common.DeleteRequest;
import com.arong.biBackend.common.ErrorCode;
import com.arong.biBackend.common.ResultUtils;
import com.arong.biBackend.constant.CommonConstant;
import com.arong.biBackend.constant.UserConstant;
import com.arong.biBackend.exception.BusinessException;
import com.arong.biBackend.exception.ThrowUtils;
import com.arong.biBackend.service.ChartService;
import com.arong.biBackend.service.UserService;
import com.arong.biBackend.utils.SqlUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

/**
 * 图表接口
 *
 */
@RestController
@RequestMapping("/chart")
@Slf4j
public class ChartController {

    @Resource
    private ChartService chartService;

    @Resource
    private UserService userService;

    @Resource
    private CosManager cosManager;

    @Resource
    private AIManager aiManager;

    @Resource
    private RedisLimiterManager redisLimiterManager;

    @Resource
    private ThreadPoolExecutor threadPoolExecutor;

    @Resource
    private GuavaRetryManager guavaRetryManager;

    @Resource
    private BiMessageProducer biMessageProducer;

    @Resource
    private ChartMapper chartMapper;



    // region 增删改查

    /**
     * 创建
     *
     * @param chartAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addChart(@RequestBody ChartAddRequest chartAddRequest, HttpServletRequest request) {
        if (chartAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Chart chart = new Chart();
        BeanUtils.copyProperties(chartAddRequest, chart);
        User loginUser = userService.getLoginUser(request);
        chart.setUserId(loginUser.getId());
        boolean result = chartService.save(chart);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        long newChartId = chart.getId();
        return ResultUtils.success(newChartId);
    }

    /**
     * 删除
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteChart(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        Chart oldChart = chartService.getById(id);
        ThrowUtils.throwIf(oldChart == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldChart.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean b = chartService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 更新（仅管理员）
     *
     * @param chartUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateChart(@RequestBody ChartUpdateRequest chartUpdateRequest) {
        if (chartUpdateRequest == null || chartUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Chart chart = new Chart();
        BeanUtils.copyProperties(chartUpdateRequest, chart);
        long id = chartUpdateRequest.getId();
        // 判断是否存在
        Chart oldChart = chartService.getById(id);
        ThrowUtils.throwIf(oldChart == null, ErrorCode.NOT_FOUND_ERROR);
        boolean result = chartService.updateById(chart);
        return ResultUtils.success(result);
    }

    /**
     * 根据 id 获取
     *
     * @param id
     * @return
     */
    @GetMapping("/get")
    public BaseResponse<Chart> getChartById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Chart chart = chartService.getById(id);
        if (chart == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        return ResultUtils.success(chart);
    }

    /**
     * 分页获取列表（封装类）
     *
     * @param chartQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page")
    public BaseResponse<Page<Chart>> listChartByPage(@RequestBody ChartQueryRequest chartQueryRequest,
            HttpServletRequest request) {
        long current = chartQueryRequest.getCurrent();
        long size = chartQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<Chart> chartPage = chartService.page(new Page<>(current, size),
                getQueryWrapper(chartQueryRequest));
        return ResultUtils.success(chartPage);
    }

    /**
     * 分页获取当前用户创建的资源列表
     *
     * @param chartQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/page")
    public BaseResponse<Page<Chart>> listMyChartByPage(@RequestBody ChartQueryRequest chartQueryRequest,
            HttpServletRequest request) {
        if (chartQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        chartQueryRequest.setUserId(loginUser.getId());
        long current = chartQueryRequest.getCurrent();
        long size = chartQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<Chart> chartPage = chartService.page(new Page<>(current, size),
                getQueryWrapper(chartQueryRequest));
        return ResultUtils.success(chartPage);
    }

    // endregion

    /**
     * 编辑（用户）
     *
     * @param chartEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editChart(@RequestBody ChartEditRequest chartEditRequest, HttpServletRequest request) {
        if (chartEditRequest == null || chartEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Chart chart = new Chart();
        BeanUtils.copyProperties(chartEditRequest, chart);
        User loginUser = userService.getLoginUser(request);
        long id = chartEditRequest.getId();
        // 判断是否存在
        Chart oldChart = chartService.getById(id);
        ThrowUtils.throwIf(oldChart == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑
        if (!oldChart.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean result = chartService.updateById(chart);
        return ResultUtils.success(result);
    }

    /**
     * 获取查询包装类
     *
     * @param chartQueryRequest
     * @return
     */
    private QueryWrapper<Chart> getQueryWrapper(ChartQueryRequest chartQueryRequest) {
        QueryWrapper<Chart> queryWrapper = new QueryWrapper<>();
        if (chartQueryRequest == null) {
            return queryWrapper;
        }
        Long id = chartQueryRequest.getId();
        String name = chartQueryRequest.getName();
        String goal = chartQueryRequest.getGoal();
        String chartType = chartQueryRequest.getChartType();
        Long userId = chartQueryRequest.getUserId();
        String sortField = chartQueryRequest.getSortField();
        String sortOrder = chartQueryRequest.getSortOrder();
        String createTime = chartQueryRequest.getCreateTime();
        String status = chartQueryRequest.getStatus();
        String date = null;
        if(createTime != null && !"".equals(createTime)) {
            DateTime dateTime = DateUtil.parse(createTime.substring(0, createTime.indexOf('T')), "yyyy-MM-dd");
            date = DateUtil.formatDate(dateTime);
        }


        queryWrapper.eq(id != null && id > 0, "id", id);
        queryWrapper.like(StringUtils.isNotBlank(goal), "goal", goal);
        queryWrapper.like(StringUtils.isNotBlank(name), "name", name);
        queryWrapper.eq(StringUtils.isNotBlank(chartType), "chartType", chartType);
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId), "userId", userId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(status), "status", status);
        queryWrapper.like(ObjectUtils.isNotEmpty(date), "createTime", date);
        queryWrapper.eq("isDelete", false);
        queryWrapper.orderBy(SqlUtils.validSortField(sortField), sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return queryWrapper;
    }

    /**
     * 文件上传
     *
     * @param multipartFile
     * @param uploadFileRequest
     * @param request
     * @return
     */
    @PostMapping("/upload")
    public BaseResponse<String> uploadFile(@RequestPart("file") MultipartFile multipartFile,
                                           UploadFileRequest uploadFileRequest, HttpServletRequest request) {
        String biz = uploadFileRequest.getBiz();
        FileUploadBizEnum fileUploadBizEnum = FileUploadBizEnum.getEnumByValue(biz);
        if (fileUploadBizEnum == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        validFile(multipartFile, fileUploadBizEnum);
        User loginUser = userService.getLoginUser(request);
        // 文件目录：根据业务、用户来划分
        String uuid = RandomStringUtils.randomAlphanumeric(8);
        String filename = uuid + "-" + multipartFile.getOriginalFilename();
        String filepath = String.format("/%s/%s/%s", fileUploadBizEnum.getValue(), loginUser.getId(), filename);
        File file = null;
        try {
            // 上传文件
            file = File.createTempFile(filepath, null);
            multipartFile.transferTo(file);
            cosManager.putObject(filepath, file);
            // 返回可访问地址
            return ResultUtils.success(FileConstant.COS_HOST + filepath);
        } catch (Exception e) {
            log.error("file upload error, filepath = " + filepath, e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "上传失败");
        } finally {
            if (file != null) {
                // 删除临时文件
                boolean delete = file.delete();
                if (!delete) {
                    log.error("file delete error, filepath = {}", filepath);
                }
            }
        }
    }

    /**
     * 校验文件
     *
     * @param multipartFile
     * @param fileUploadBizEnum 业务类型
     */
    private void validFile(MultipartFile multipartFile, FileUploadBizEnum fileUploadBizEnum) {
        // 文件大小
        long fileSize = multipartFile.getSize();
        // 文件后缀
        String fileSuffix = FileUtil.getSuffix(multipartFile.getOriginalFilename());
        final long ONE_M = 1024 * 1024L;
        if (FileUploadBizEnum.USER_AVATAR.equals(fileUploadBizEnum)) {
            if (fileSize > ONE_M) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件大小不能超过 1M");
            }
            if (!Arrays.asList("jpeg", "jpg", "svg", "png", "webp").contains(fileSuffix)) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件类型错误");
            }
        }
    }

    @Transactional
    @PostMapping("/gen")
    public BaseResponse<BIResponse> getChartByAi(@RequestPart(value = "file", required = false) MultipartFile multipartFile,
                                             String res,
                                             GenChartByAiRequest genChartByAiRequest,
                                             HttpServletRequest request) {
        String name = genChartByAiRequest.getName();
        String goal = genChartByAiRequest.getGoal();
        String chartType = genChartByAiRequest.getChartType();

        // 如果分析目标为空，就抛出请求参数错误异常，并给出提示
        ThrowUtils.throwIf(StringUtils.isBlank(goal), ErrorCode.PARAMS_ERROR, "目标为空");
        // 如果名称不为空，并且名称长度大于100，就抛出异常，并给出提示
        ThrowUtils.throwIf(StringUtils.isNotBlank(name) && name.length() > 100, ErrorCode.PARAMS_ERROR, "名称过长");

        /**
         * 校验文件
         * 但是优先选择前端直接传送过来的数据
         * 数据格式：
         * 日期,用户数
         * 字符串,数字
         * 1号,10
         * 2号,20
         * 3号,30
         * 4号,90
         * 5号,0
         * 6号,10
         * 7号,20
         *
         * 分析文件大小
         *
         * 分析文件后最
         */
        if(multipartFile != null && !multipartFile.isEmpty()) {
            // 文件大小校验
            long size = multipartFile.getSize();
            ;
            final long ONE_MB = 1024 * 1024L;
            ThrowUtils.throwIf(size > 10 * ONE_MB, ErrorCode.PARAMS_ERROR, "文件大小过大，请控制在10M以下");

            // 后缀校验
            String suffix = FileUtil.getSuffix(multipartFile.getOriginalFilename());
            final List<String> validFileSuffixList = Arrays.asList("xlsx", "csv", "xls");
            ThrowUtils.throwIf(!validFileSuffixList.contains(suffix), ErrorCode.OPERATION_ERROR, "文件格式不正确");

            if(res == null) {
                res = ExcelUtils.excelToCsv(multipartFile);
            }
        }

        StringBuilder userInput = new StringBuilder();
        // 分析目标
        if(StringUtils.isNotBlank(chartType)) {
            userInput.append("，请使用").append(chartType).append("进行分析。");
        }
        userInput.append("分析需求：").append("\n").append(goal);

        // 读取上传文件的用户
        User loginUser = userService.getLoginUser(request);

        // 校验有无生成同名文件
        QueryWrapper<Chart> chartQueryWrapper = new QueryWrapper<>();
        chartQueryWrapper.lambda()
                .eq(Chart::getUserId, loginUser.getId())
                .eq(Chart::getName, name);
        List<Chart> list = chartService.list(chartQueryWrapper);
        if(!list.isEmpty()) {
            log.error("分析文件不能同名", name);
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "分析文件不能同名");
        }

        // 限流判断，每个用户独立一个限流器
        redisLimiterManager.doRateLimit("genChartByAi_" + loginUser.getId());

        userInput.append("原始数据：").append("\n").append(res);

        // 原始数据生成表
        chartService.genTableByCSVData(loginUser.getId() + name, res);

        long BiModelId = 1694262097770192898L;

        String result = aiManager.doChat(BiModelId, userInput.toString());
        String[] spilts = result.split("【【【【【");

        if(spilts.length < 3) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "AI生成错误");
        }

        String genChart = spilts[1].trim();

        String genResult = spilts[2].trim();

        Chart chart = new Chart();
        chart.setName(name);
        chart.setGoal(goal);
        chart.setUserName(loginUser.getUserName());
        chart.setChartData(res);
        chart.setChartType(chartType);
        chart.setGenChart(genChart);
        chart.setGenResult(genResult);
        chart.setStatus("succeed");
        chart.setUserId(loginUser.getId());

        boolean save = chartService.save(chart);
        ThrowUtils.throwIf(!save, ErrorCode.SYSTEM_ERROR, "图表保存失败");



        BIResponse biResponse = new BIResponse();
        biResponse.setGenChart(genChart);
        biResponse.setGenResult(genResult);
        biResponse.setChartId(chart.getId());
        return ResultUtils.success(biResponse);
        }

    @Transactional
    @PostMapping("/gen/async")
    public BaseResponse<BIResponse> getChartByAiAsync(@RequestPart(value = "file", required = false) MultipartFile multipartFile,
                                                 String res,
                                                 GenChartByAiRequest genChartByAiRequest,
                                                 HttpServletRequest request){
        String name = genChartByAiRequest.getName();
        String goal = genChartByAiRequest.getGoal();
        String chartType = genChartByAiRequest.getChartType();

        // 如果分析目标为空，就抛出请求参数错误异常，并给出提示
        ThrowUtils.throwIf(StringUtils.isBlank(goal), ErrorCode.PARAMS_ERROR, "目标为空");
        // 如果名称不为空，并且名称长度大于100，就抛出异常，并给出提示
        ThrowUtils.throwIf(StringUtils.isNotBlank(name) && name.length() > 100, ErrorCode.PARAMS_ERROR, "名称过长");

        /**
         * 校验文件
         * 但是优先选择前端直接传送过来的数据
         * 数据格式：
         * 日期,用户数
         * 字符串,数字
         * 1号,10
         * 2号,20
         * 3号,30
         * 4号,90
         * 5号,0
         * 6号,10
         * 7号,20
         *
         * 分析文件大小
         *
         * 分析文件后最
         */
        if(multipartFile != null && !multipartFile.isEmpty()) {
            // 文件大小校验
            long size = multipartFile.getSize();
            ;
            final long ONE_MB = 1024 * 1024L;
            ThrowUtils.throwIf(size > 10 * ONE_MB, ErrorCode.PARAMS_ERROR, "文件大小过大，请控制在10M以下");

            // 后缀校验
            String suffix = FileUtil.getSuffix(multipartFile.getOriginalFilename());
            final List<String> validFileSuffixList = Arrays.asList("xlsx", "csv", "xls");
            ThrowUtils.throwIf(!validFileSuffixList.contains(suffix), ErrorCode.OPERATION_ERROR, "文件格式不正确");

            if(res == null) {
                res = ExcelUtils.excelToCsv(multipartFile);
            }
        }

        StringBuilder userInput = new StringBuilder();
        // 分析目标
        if(StringUtils.isNotBlank(chartType)) {
            userInput.append("，请使用").append(chartType).append("进行分析。");
        }
        userInput.append("分析需求：").append("\n").append(goal);

        // 读取上传文件的用户
        User loginUser = userService.getLoginUser(request);

        // 限流判断，每个用户独立一个限流器
        redisLimiterManager.doRateLimit("genChartByAi_" + loginUser.getId());

        // 校验有无生成同名文件
        QueryWrapper<Chart> chartQueryWrapper = new QueryWrapper<>();
        chartQueryWrapper.lambda()
                .eq(Chart::getUserId, loginUser.getId())
                .eq(Chart::getName, name);
        List<Chart> list = chartService.list(chartQueryWrapper);
        if(!list.isEmpty()) {
            log.error("分析文件不能同名", name);
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "分析文件不能同名");
        }

        // 限流判断，每个用户独立一个限流器
        redisLimiterManager.doRateLimit("genChartByAi_" + loginUser.getId());

        userInput.append("原始数据：").append("\n").append(res);

        // 原始数据生成表
        chartService.genTableByCSVData(loginUser.getId() + name, res);

        Chart chart = new Chart();
        chart.setName(name);
        chart.setGoal(goal);
        chart.setUserName(loginUser.getUserName());
        chart.setChartData(res);
        chart.setChartType(chartType);
//        chart.setGenChart(genChart);
//        chart.setGenResult(genResult);
        // 设置任务状态为排队中
        chart.setStatus("wait");
        chart.setUserId(loginUser.getId());

        boolean save = chartService.save(chart);
        ThrowUtils.throwIf(!save, ErrorCode.SYSTEM_ERROR, "图表保存失败");

        Callable<Void> callable = () -> {
            Chart updateChart = new Chart();
            updateChart.setId(chart.getId());
            // 任务状态改为执行中
            updateChart.setStatus("running");
            boolean b = chartService.updateById(updateChart);
            if (!b) {
                handleChartUpdateError(chart.getId(), "更新图表执行中状态失败");
                throw new BusinessException(ErrorCode.PARAMS_ERROR, chart.getId() + "： 更新图表执行中状态失败");
            }

            long BiModelId = 1694262097770192898L;
            String result = aiManager.doChat(BiModelId, userInput.toString());
            String[] splits = result.split("【【【【【");

            if (splits.length < 3) {
                handleChartUpdateError(chart.getId(), "AI生成错误");
                throw new BusinessException(ErrorCode.PARAMS_ERROR, chart.getId() + "： AI生成错误");
            }
            String genChart = splits[1].trim();
            String genResult = splits[2].trim();
            // 调用AI得到结果之后,再更新一次
            Chart updateChartResult = new Chart();
            updateChartResult.setId(chart.getId());
            updateChartResult.setGenChart(genChart);
            updateChartResult.setGenResult(genResult);
            updateChartResult.setStatus("succeed");
            boolean updateResult = chartService.updateById(updateChartResult);
            if (!updateResult) {
                handleChartUpdateError(chart.getId(), "更新图表成功状态失败");
            }
            return null;
        };

        // 提交任务
        Future<Object> future = threadPoolExecutor.submit(() -> {
            // 重试
            try {
                guavaRetryManager.defaultRetryer().call(callable);
            } catch (Exception e) {
                handleChartUpdateError(chart.getId(), "超时");
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "ai生成失败，请联系后台");
            }
            return null;
        });

        try {
            future.get(5, TimeUnit.MINUTES);
        } catch (Exception e) {
            handleChartUpdateError(chart.getId(), "超时");
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "任务超时");
        }


        BIResponse biResponse = new BIResponse();
//        biResponse.setGenChart(genChart);
//        biResponse.setGenResult(genResult);
        biResponse.setChartId(chart.getId());
        return ResultUtils.success(biResponse);
    }

    @Transactional
    @PostMapping("/gen/async/mq")
    public BaseResponse<BIResponse> getChartByAiAsyncMq(@RequestPart(value = "file", required = false) MultipartFile multipartFile,
                                                      String res,
                                                      GenChartByAiRequest genChartByAiRequest,
                                                      HttpServletRequest request){
        String name = genChartByAiRequest.getName();
        String goal = genChartByAiRequest.getGoal();
        String chartType = genChartByAiRequest.getChartType();

        // 如果分析目标为空，就抛出请求参数错误异常，并给出提示
        ThrowUtils.throwIf(StringUtils.isBlank(goal), ErrorCode.PARAMS_ERROR, "目标为空");
        // 如果名称不为空，并且名称长度大于100，就抛出异常，并给出提示
        ThrowUtils.throwIf(StringUtils.isNotBlank(name) && name.length() > 100, ErrorCode.PARAMS_ERROR, "名称过长");

        /**
         * 校验文件
         * 但是优先选择前端直接传送过来的数据
         * 数据格式：
         * 日期,用户数
         * 字符串,数字
         * 1号,10
         * 2号,20
         * 3号,30
         * 4号,90
         * 5号,0
         * 6号,10
         * 7号,20
         *
         * 分析文件大小
         *
         * 分析文件后最
         */
        if(multipartFile != null && !multipartFile.isEmpty()) {
            // 文件大小校验
            long size = multipartFile.getSize();
            ;
            final long ONE_MB = 1024 * 1024L;
            ThrowUtils.throwIf(size > 10 * ONE_MB, ErrorCode.PARAMS_ERROR, "文件大小过大，请控制在10M以下");

            // 后缀校验
            String suffix = FileUtil.getSuffix(multipartFile.getOriginalFilename());
            final List<String> validFileSuffixList = Arrays.asList("xlsx", "csv", "xls");
            ThrowUtils.throwIf(!validFileSuffixList.contains(suffix), ErrorCode.OPERATION_ERROR, "文件格式不正确");

            if(res == null) {
                res = ExcelUtils.excelToCsv(multipartFile);
            }
        }

        StringBuilder userInput = new StringBuilder();
        // 分析目标
        if(StringUtils.isNotBlank(chartType)) {
            userInput.append("，请使用").append(chartType).append("进行分析。");
        }
        userInput.append("分析需求：").append("\n").append(goal);

        // 读取上传文件的用户
        User loginUser = userService.getLoginUser(request);
        if(ObjectUtils.isEmpty(loginUser)) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }

        // 校验有无生成同名文件
        QueryWrapper<Chart> chartQueryWrapper = new QueryWrapper<>();
        chartQueryWrapper.lambda()
                .eq(Chart::getUserId, loginUser.getId())
                .eq(Chart::getName, name);
        List<Chart> list = chartService.list(chartQueryWrapper);
        if(!list.isEmpty()) {
            log.error("分析文件不能同名", name);
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "分析文件不能同名");
        }

        // 限流判断，每个用户独立一个限流器
        redisLimiterManager.doRateLimit("genChartByAi_" + loginUser.getId());

        userInput.append("原始数据：").append("\n").append(res);

        // 原始数据生成表
        chartService.genTableByCSVData(loginUser.getId() + name, res);

        Chart chart = new Chart();
        chart.setName(name);
        chart.setGoal(goal);
        chart.setUserName(loginUser.getUserName());
        chart.setChartData(res);
        chart.setChartType(chartType);
//        chart.setGenChart(genChart);
//        chart.setGenResult(genResult);
        // 设置任务状态为排队中
        chart.setStatus("wait");
        chart.setUserId(loginUser.getId());

        boolean save = chartService.save(chart);
        ThrowUtils.throwIf(!save, ErrorCode.SYSTEM_ERROR, "图表保存失败");

        biMessageProducer.sendMessage(String.valueOf(chart.getId()));


        BIResponse biResponse = new BIResponse();
//        biResponse.setGenChart(genChart);
//        biResponse.setGenResult(genResult);
        biResponse.setChartId(chart.getId());
        return ResultUtils.success(biResponse);
    }

    @PostMapping("/detailChart")
    public BaseResponse<List<Map<String, Object>>> getDetailChartList(@RequestBody DetailTableDto detailTableDto) {
        List<Map<String, Object>> maps = chartMapper.queryChartData(detailTableDto);
        return ResultUtils.success(maps);
    }

    private void handleChartUpdateError(long chartId, String errMessage) {
        Chart updateChartResult = new Chart();
        updateChartResult.setId(chartId);
        updateChartResult.setStatus("failed");
        updateChartResult.setExecMessage(errMessage);
        boolean b = chartService.updateById(updateChartResult);
        if(!b) {
            log.error("更新图表状态失败" + chartId + "," + errMessage);
        }
    }
}

